package com.hcj.springcloud.ObserverPattern;

import java.util.ArrayList;
import java.util.List;

/**
 * 被观察的对象
 */
public class Subject {
    private List<Observer> observers = new ArrayList<>();

    private int state;

    public int getState() {
        return state;
    }

    public void setState(int state) {
        this.state = state;
        notifyAllObservers();
    }

    /**
     * 添加观察者
     * @param observer
     */
    public void attach(Observer observer){
        observers.add(observer);
    }

    /**
     * 移除观察者
     * @param observer
     */
    public void notAttach(Observer observer){
        observers.remove(observer);
    }

    private void notifyAllObservers() {
        for(Observer observer: observers){
            observer.update();
        }
    }
}
